﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DispatchAssist.Weather.Interfaces;
using DispatchAssist.Weather.Entities;
using DispatchAssist.Weather.Helper;
using System.Net;
using System.IO;
using System.Drawing;
using System.Threading;

namespace DispatchAssist.Weather.Providers
{
    class WeatherNetDisplayProvider: IWeatherDisplayProvider
    {


        public IWeatherMapProvider WeatherMapProvider { get; private set; }

        public IWeatherMapInfo WeatherMapInfo { get; private set; }

        public IGetPics Pics { get; private set; }

        private bool MapInfoChanged = false;
        private bool PicDisplayStarted = false;

        private static object lockObj = new object();

        public bool IsPlay { get; set; }
        /// <summary>
        /// 图片相隔1000ms显示
        /// </summary>
        public const int PlayInterval = 1000;
        /// <summary>
        /// 每次加载图片最大失败次数
        /// </summary>
        public const int MaxErrorCount = 10;
        public int ErrorCount = 0;
        public event DisplayWeatherMapEventHandler DisplayWeatherMap;

        public WeatherNetDisplayProvider(IWeatherMapProvider mapProvider)
        {
            WeatherMapProvider = mapProvider;


            try
            {
                client = new WebClient();
                client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
                client.Credentials = CredentialCache.DefaultCredentials;
                client.Proxy = WebRequest.GetSystemWebProxy();
            }
            catch
            {
            }

        }
        public WeatherNetDisplayProvider(IWeatherMapProvider mapProvider, IWeatherMapInfo mapInfo)
            : this(mapProvider)
        {
            WeatherMapInfo = mapInfo;
        }

        private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            Thread thread = new Thread(() =>
            {
                try
                {
                    if (e.Result != null && DisplayWeatherMap != null)
                    {
                        DisplayWeatherMap(null, Image.FromStream(e.Result));
                        ErrorCount = 0;//成功后重置
                    }
                }
                catch (Exception ex)
                {
                    ErrorCount++;
                    if (ErrorCount < MaxErrorCount)
                    {//一直显示前一张图，直到错误达到MaxErrorCount为止
                        Pics.SetPreviousDateTime();
                        Show();
                    }
                    CarolLib.Log.Instance.Error("下载最新图片错误", ex);
                }
            });
            thread.Start();
        }


        /// <summary>
        /// 使用IE代理
        /// </summary>
        private WebClient client = null;

        public void Show()
        {
            ThreadPool.QueueUserWorkItem(s =>
            {
                PicDisplayStarted = true;
                try
                {
                    var uri = new Uri(Pics.GetNewestPic());

                    var result = client.OpenRead(uri);

                    if (result != null && DisplayWeatherMap != null)
                    {
                        lock (lockObj)
                        {
                            if (MapInfoChanged)
                            {
                                MapInfoChanged = false;
                                return;
                            }
                        }
                        DisplayWeatherMap(WeatherMapInfo, Image.FromStream(result));
                        PicDisplayStarted = false;
                        ErrorCount = 0;//成功后重置
                    }
                }
                catch (Exception ex)
                {
                    ErrorCount++;
                    if (ErrorCount < MaxErrorCount)
                    {//一直显示前一张图，直到错误达到MaxErrorCount为止
                        if (!MapInfoChanged)
                        {
                            Pics.SetPreviousDateTime();
                            Show();
                        }
                        else
                        {
                            MapInfoChanged = false;
                            PicDisplayStarted = false;
                            ErrorCount = 0;//成功后重置
                        }
                    }
                    CarolLib.Log.Instance.Error("下载最新图片错误", ex);
                }
            });

        }


        public void Play(double time)
        {
            IsPlay = true;

            new Thread(() =>
           {
               try
               {
                   CircularQueue<Image> images = new CircularQueue<Image>();
                   ThreadPool.QueueUserWorkItem(s =>
                   {//此线程池不断地去显示图片
                       try
                       {
                           while (IsPlay)
                           {
                               Thread.Sleep(PlayInterval);
                               images.MoveNext();
                               if (images.Current != null)
                               {
                                   if (!IsPlay)
                                       return;

                                   DisplayWeatherMap(WeatherMapInfo, images.Current);
                               }
                           }
                       }
                       catch (Exception ex)
                       {
                           CarolLib.Log.Instance.Error("循环显示图片错误", ex);
                       }
                   });


                   var picUrls = Pics.GetAnimatePics(time);
                   foreach (var pic in picUrls)
                   {//下载所有图片
                       if (!IsPlay)
                           return;

                       try
                       {
                           images.EnQueue(Image.FromStream(client.OpenRead(new Uri(pic))));
                       }
                       catch (Exception ex)
                       {
                           CarolLib.Log.Instance.Error("下载图片错误", ex);
                       }
                   }
               }
               catch (Exception ex)
               {
                   CarolLib.Log.Instance.Error(ex);
               }
           }).Start();
        }

        public void Suspend()
        {
            IsPlay = false;
        }

        public void FirstPic()
        {
            throw new NotImplementedException();
        }

        public void LastPic()
        {
            throw new NotImplementedException();
        }

        public void ForwardPic()
        {
            throw new NotImplementedException();
        }

        public void BackwardPic()
        {
            throw new NotImplementedException();
        }

        public void ZoomOut()
        {
            throw new NotImplementedException();
        }

        public void ZoomIn()
        {
            throw new NotImplementedException();
        }

        public void Move(System.Drawing.Point point)
        {
            throw new NotImplementedException();
        }

        public void ShowAirports()
        {
            throw new NotImplementedException();
        }

        public void HideAirports()
        {
            throw new NotImplementedException();
        }

        public void SetAirportColor(System.Drawing.Color color)
        {
            throw new NotImplementedException();
        }

        public void SelecteWeatherMapInfo(IWeatherMapInfo mapInfo)
        {
            WeatherMapInfo = mapInfo;

            Pics = ProviderHelper.GetWeatherMapInfo(mapInfo);

            lock (lockObj)
            {
                if (PicDisplayStarted)
                {
                    MapInfoChanged = true;
                }
            }
        }
    }
}
